const express = require('express')
const router = express.Router()
const multer = require('multer')

const storage = multer.diskStorage({
    // 指定文件路径
    destination: (req, file, cb) => {
        cb(null, './public/uploads')
    },
    // 指定文件名
    filename: (req, file, cb) => {
        const suffix = file.originalname.split('.').pop()
        cb(null, `${ (new Date()).getTime() + parseInt(Math.random()*9999) }.${suffix}`)
    }
})
const upload = multer({ storage })

var param = {
    meta: {
        code: 200,
        msg: ''
    },
    data: ''
}

/**
 * @api {post} /file/upload 上传图片
 * @apiName upload
 * @apiGroup image
 *
 * @apiParam {file} image 图片(required)
 *
 * @apiSuccess {Object} meta 状态信息 
 * @apiSuccess {Object} data { type,path }
 * 
 * @apiError 402 上传失败，图片尺寸大于400K
 * @apiError 403 上传失败，文件格式有误
 */
router.post('/upload', upload.single('image'), (req, res) => {
    // image 为图片的key
    const { size, filename, mimetype } = req.file
    let types = ['jpg', 'jpeg', 'png', 'gif']
    const type = mimetype.split('/')[1]
    if(!types.some(i => type === i)) {
        param.meta.code = 403
        param.meta.msg = '上传失败，文件格式有误'
        return res.send(param)
    }
    if(size>400*1024) {
        param.meta.code = 402
        param.meta.msg = '上传失败，图片尺寸大于400K'
        return res.send(param)
    }
    param.meta.msg = '上传成功'
    param.data = { type, path: `/public/uploads/${filename}` }
    res.send(param)
})

module.exports = router